import { getUserInfoAPI, loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

// user模块
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    routes: [] // 路由数组
  },
  mutations: {
    saveToken(state, payload) {
      state.token = payload
    },
    saveUserInfo(state, payload) {
      state.userInfo = payload
    },
    saveRoutes(state, payload) {
      state.routes = payload
    }
  },
  actions: {
    async loginAction({ commit }, payload) {
      // 调用登录api await 等待
      const result = await loginAPI(payload)
      // 成功 存token vuex 和 本地
      commit('saveToken', result.data)
      // 存本地
      setToken(result.data)
      Message.success('登录成功')
      router.push('/')
    },
    async getUserInfoAction({ commit }) {
      const result = await getUserInfoAPI()
      commit('saveUserInfo', result.data)
      console.log(result)
    }
  }
}

